import * as crypto from 'crypto'
import * as url from 'url'
import config from '../config'

const TOKEN = config.wechat.TOKEN

// sha1 加密
function sha1(str) {
  var md5sum = crypto.createHash("sha1");
  md5sum.update(str);
  str = md5sum.digest("hex");
  return str;
}

// 验证 token
export function validateToken(req, res) {
  const query = url.parse(req.url, true).query;
  const signature = query.signature;
  const echostr = query.echostr;
  const timestamp = query.timestamp;
  const nonce = query.nonce;

  const oriArray = [nonce, timestamp, TOKEN]
  oriArray.sort();
  const original = oriArray.join('');

  console.log("Original str : " + original);
  console.log("Signature : " + signature);
  const scyptoString = sha1(original);

  if (signature == scyptoString) {
    res.end(echostr);
    console.log("Confirm and send echo back");
  } else {
    res.end("false");
    console.log("Failed!");
  }
}

// 处理字符串
export function raw (args) {
  let keys = Object.keys(args);
  keys = keys.sort();
  let newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });

  let string = '';
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k];
  }
  string = string.substr(1);
  return string;
};

/**
 * @synopsis 签名算法
 *
 * @param jsapi_ticket 用于签名的 jsapi_ticket
 * @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
 *
 * @returns
 */
export function sign (jsapi_ticket, url, nonce, timestamp) {
  const ret = {
    jsapi_ticket: jsapi_ticket,
    nonceStr: nonce,
    timestamp: timestamp,
    url: url
  };
  var string = raw(ret);
  return sha1(string);
}